﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.JCI.Common.Utility;
using System.Data;
using System.Data.Common;
using Microsoft.JCI.Common.Entity;

namespace Microsoft.JCI.Dal
{
    public partial class SysFunctionDal 
    {
        /// <summary>
        /// 根据角色构造功能点树
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        public DataTable BuildAllFunction(Guid RoleID)
        {
            string sql = @"select A.*, 
case when B.RoleID IS NULL then 0 else 1 end as IsChecked
from Jci_Sys_Function A
left join Jci_Sys_RoleFunctionRelation B ON A.FuncID = B.FuncID and B.RoleID =@RoleID
";
            DbCommand dbcommand = CurrentDatabase.GetSqlStringCommand(sql);
            CurrentDatabase.AddInParameter(dbcommand, "@RoleID", DbType.Guid, RoleID);

            return CurrentDatabase.ExecuteDataSet(dbcommand).Tables[0];
        }

        /// <summary>
        /// 根据用户获取功能点树
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public List<SysFunctionEntity> LoadTreeFunctionEntitiesByUserID(Guid UserID)
        {
            List<SysFunctionEntity> entities = new List<SysFunctionEntity>();
            string sql = @"select distinct C.* from Jci_Sys_RoleFunctionRelation A join Jci_Sys_UserRoleRelation B on
A.RoleID = B.RoleID 
join Jci_Sys_Function C on A.FuncID = C.FuncID
where B.UserID = @UserID and C.IsMenu = 1 order by FuncID"; 
            DbCommand dbcommand = CurrentDatabase.GetSqlStringCommand(sql);
            CurrentDatabase.AddInParameter(dbcommand, "@UserID", DbType.Guid, UserID);

            using (IDataReader reader = CurrentDatabase.ExecuteReader(dbcommand))
            {
                entities = base.GetListFromReader<SysFunctionEntity>(reader);
            }

            return entities;
        }
        /// <summary>
        /// 获取用户具有的权限
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public List<SysFunctionEntity> LoadUserHavedFunction(Guid UserID)
        {
            List<SysFunctionEntity> entities = new List<SysFunctionEntity>();
            string sql = @"select C.* from Jci_Sys_RoleFunctionRelation A join Jci_Sys_UserRoleRelation B on
A.RoleID = B.RoleID 
join Jci_Sys_Function C on A.FuncID = C.FuncID
where B.UserID = @UserID";
            DbCommand dbcommand = CurrentDatabase.GetSqlStringCommand(sql);
            CurrentDatabase.AddInParameter(dbcommand, "@UserID", DbType.Guid, UserID);

            using (IDataReader reader = CurrentDatabase.ExecuteReader(dbcommand))
            {
                entities = base.GetListFromReader<SysFunctionEntity>(reader);
            }

            return entities;
        }
    }
}
